#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <errno.h>

#define BUFFER_SIZE 1024
int main()
{
    int pipefd1[2],pipefd2[2];
    char buffer[BUFFER_SIZE];
    ssize_t nbytes;

    //创建两个管道
    if(pipe(pipefd1) == -1){
        perror("pipe1");
        return 1;
    }

    if(pipe(pipefd2) == -1){
        perror("pipe2");
        close(pipefd1[0]);
        close(pipefd1[1]);
    }

    //向第一个管道写入数据
    write(pipefd1[1],"Hello, Splice!",14);
    //使用splice函数将数据从第一个管道传输到第二个管道
    nbytes = splice(pipefd1[0],NULL,pipefd2[1],NULL,BUFFER_SIZE,0);
    if(nbytes == -1){
        perror("splice");
        close(pipefd1[0]);
        close(pipefd1[1]);
        close(pipefd2[0]);
        close(pipefd2[1]);
        return 1;
    }

    //从第二个管道读取数据并打印
    nbytes = read(pipefd2[0],buffer,BUFFER_SIZE);
    if(nbytes == -1){
        perror("splice");
        close(pipefd1[0]);
        close(pipefd1[1]);
        close(pipefd2[0]);
        close(pipefd2[1]);
        return 1;
    }
    buffer[nbytes] = '\0';
    printf("Received data:%s\n",buffer);

    //关闭管道文件描述符
    close(pipefd1[0]);
    close(pipefd1[1]);
    close(pipefd2[0]);
    close(pipefd2[1]);
    return 0;
}